package tech.aiflowy.auth.config;

import cn.dev33.satoken.exception.BackResultException;
import cn.dev33.satoken.exception.StopMatchException;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaAnnotationStrategy;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.aiflowy.auth.entity.LoginVO;
import tech.aiflowy.auth.service.AuthService;
import tech.aiflowy.common.util.SpringContextUtil;
import tech.aiflowy.common.util.StringUtil;
import tech.aiflowy.system.entity.SysToken;
import tech.aiflowy.system.service.SysTokenService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class SaApiInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {


        String token=StpUtil.getTokenValue();
        if(StringUtils.isNotBlank(token)){
            Object obj  = StpUtil.getLoginIdByToken(token);
            if(obj==null){
                SysTokenService tokenService=SpringContextUtil.getBean(SysTokenService.class);
                AuthService authService=SpringContextUtil.getBean(AuthService.class);
                 SysToken res = tokenService.getByToken(token);
                 if(res!=null && token.equals(res.getTokenValue())){
                    authService.login(res.getCreatedBy(),token);
                 }
            }
        }
        // 通过验证
        return true;
    }
}
